import { Button, Icon, Checkbox, InputNumber, Modal } from 'antd';
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { Nav } from "../../components/Nav";
import { Head } from "../../components/Head";
import { Foot } from "../../components/Footer";


import './index.less';
import { SHOPPINGCAR_INIT, SHOPPINGCAR_UPDATE } from '../../actionCreators/actionTypes';
const confirm = Modal.confirm;

class UI extends React.Component {
    constructor() {
        super();

        // this.state = {
        //     allChecked: false
        // }

        this.goNow = this.goNow.bind(this);
        this.numChange = this.numChange.bind(this);
        this.checkAll = this.checkAll.bind(this);
        this.checkOne = this.checkOne.bind(this);
        this.delAll = this.delAll.bind(this);
    }
    componentDidMount() {
        // 获取用户名
        this.props.shoppingCarInit();
    }
    goNow() {
        this.props.history.push('/goods');
    }
    numChange(value, id) {
        this.props.numberChange(value, id);
    }

    checkOne(e, goods) {
        this.props.oneCheckedChange(e.target.checked, goods);
        // 强制更新视图（没有类似vue的深度监听）
        this.forceUpdate();
    }

    checkAll(e) {
        this.props.allCheckedChange(e.target.checked);
    }

    delAll() {

    }

    del(id) {
        return (() => {
            this.props.del(id);
        })
    }

    render() {
        let { list, user } = this.props;
        let trList = list.length == 0 ? [] : list.map(goods => {
            return (
                <tr key={goods.id}>
                    <td className="th1"><Checkbox onChange={(e) => { this.checkOne(e, goods) }} checked={goods.active}></Checkbox></td>
                    <td className="th2"><Link to={`/detail/${goods.id}`}>{goods.title}</Link></td>
                    <td>{(goods.price).toFixed(2)}</td>
                    <td className="th3"><InputNumber min={1} max={99} defaultValue={goods.count} onChange={(value) => { this.numChange(value, goods.id) }} /></td>
                    <td>{(goods.count * goods.price).toFixed(2)}</td>
                    <td><Icon type="close" className="close" onClick={this.del(goods.id)} /></td>
                </tr>
            );
        });

        let emptyCart = ((list.length == 0) || user == '') ? (
            <div className="empty">
                <div>
                    <p><Icon type="shopping-cart" style={{ fontSize: 26, verticalAlign: 'middle', marginTop: -4, marginRight: 10, color: '#aaa' }} />
                        您的购物车还是空的！如果还未登录，则<Link to="/login">登录</Link>后，将显示您之前加入的商品。
                    </p>
                    <Button onClick={this.goNow}>马上购物</Button>
                </div>
            </div>) : (
                <div className="notEmpty">
                    <h3>我的购物车</h3>
                    <table>
                        <tbody>
                            <tr className="thead">
                                <th className="th1"><Checkbox onChange={this.checkAll} checked={this.props.allChecked}>全选</Checkbox></th>
                                <th className="th2">商品信息</th>
                                <th >单价</th>
                                <th className="th3">数量</th>
                                <th >小计</th>
                                <th className="th6">操作</th>
                            </tr>
                            {trList}
                        </tbody>
                    </table>
                    <div className="total clearfix">
                        <div className="fl">
                            <Button onClick={this.delAll}>批量删除</Button>
                        </div>
                        <div className="fr">
                            <p>已选<span>({this.props.selectCount})</span>件  合计: ¥<span className="totalTxt">{this.props.total}</span></p>
                            <Button>结算</Button>
                        </div>
                    </div>
                </div>
            );

        return (
            <div className="shoppingcar ">
                <Nav  {...this.props} />
                <div className="cart-con w1000 clearfix">
                    {emptyCart}
                </div>
                <Foot />
            </div >
        );
    }
}

let mapStateToProps = ({ shopReducer }) => shopReducer;

let mapDispatchToProps = dispatch => {
    return {
        shoppingCarInit() {
            // 获取登录的用户
            let getUserArr = window.sessionStorage.getItem("user");
            let isLogFlag = false;
            if (getUserArr != null) {
                getUserArr = JSON.parse(getUserArr);
                getUserArr.map(i => {
                    if (i.status == true) {
                        isLogFlag = true;
                        let users = window.localStorage.getItem('cars');
                        users = JSON.parse(users).users;
                        users.map(item => {
                            if (item.user === i.name) {

                                // 添加单选状态
                                item.list.map(goods => {
                                    goods.active = false;
                                });
                                // 更新数据库
                                dispatch({
                                    type: SHOPPINGCAR_INIT,
                                    user: i.name,
                                    list: item.list,
                                });
                                return;
                            }
                        });

                        return;
                    }
                });

                if (!isLogFlag) {
                    // 将记录的user清空
                    dispatch({
                        type: SHOPPINGCAR_INIT,
                        user: '',
                        list: []
                    });
                }
            }
        },
        numberChange(value, id) {
            let loginUser = this.user;

            this.list.map(goods => {
                if (goods.id == id) {
                    goods.count = value;
                    return;
                }
            });

            // 更新数据模型
            dispatch({
                type: SHOPPINGCAR_UPDATE,
                list: this.list
            });

            // 更新数据库
            let users = window.localStorage.getItem('cars');
            users = JSON.parse(users).users;
            users.map(item => {
                if (item.user === loginUser) {
                    item.list = this.list;
                }
            });
            window.localStorage.setItem('cars', JSON.stringify({ users }));

            this.totalChange();
        },
        del(id) {
            let { list, user } = this;

            confirm({
                title: '确认删除该商品吗？',
                content: '删除后不可恢复哦',
                okText: '删除',
                cancelText: '留着吧',
                onOk() {
                    let newList = list.filter(item => {
                        return item.id != id;
                    });

                    let count = 0;
                    let total = 0;
                    newList.map(goods => {
                        if (goods.active) {
                            count = count + 1;
                            total = (total * 1 + goods.count * goods.price).toFixed(2);
                        }
                    });

                    // 更新数据模型
                    dispatch({
                        type: SHOPPINGCAR_UPDATE,
                        list: newList,
                        selectCount: count,
                        total: total
                    });

                    let users = window.localStorage.getItem('cars');
                    users = JSON.parse(users).users;
                    users.map(item => {
                        if (item.user === user) {
                            item.list = newList;
                        }
                    });

                    window.localStorage.setItem('cars', JSON.stringify({ users }));
                },
                onCancel() {
                },
            });
        },
        allCheckedChange(flag) {
            this.list.map(goods => {
                goods.active = flag;
            });
            // 更新数据模型
            dispatch({
                type: SHOPPINGCAR_UPDATE,
                list: this.list,
                allChecked: flag
            });
            // 更新总价
            this.totalChange();
        },
        oneCheckedChange(flag, goods) {
            let allFlag = true;
            // 更新当前点击的多选框的状态
            goods.active = flag;

            this.list.map(goods => {
                if (!goods.active) {
                    allFlag = false;
                }
            });

            dispatch({
                type: SHOPPINGCAR_UPDATE,
                list: this.list,
                allChecked: allFlag
            });
            // 更新总价
            this.totalChange();
        },
        totalChange() {
            let count = 0;
            let total = 0;
            this.list.map(goods => {
                if (goods.active) {
                    count = count + 1;
                    total = (total * 1 + goods.count * goods.price).toFixed(2);
                }
            });

            dispatch({
                type: SHOPPINGCAR_UPDATE,
                selectCount: count,
                total: total
            });
        }
    }
}

export let ShoppingCar = connect(mapStateToProps, mapDispatchToProps)(UI);